package com.zjdiepu.www.commpent.handler;

import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.druid.filter.config.ConfigTools;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.common.consts.RedisKeyPrefix;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.MD5Util;
import com.zjdiepu.www.commpent.RedisObjectClient;

/**
 * 项目名称：diepu-parent-rest <br/> 
 * 类名称：TokenHolder <br/>  
 * 类描述：线程变量token <br/>    
 * 创建人：xiongxiaotun <br/> 
 * 创建时间：2017年6月5日 下午12:28:28  <br/>   
 * 修改人：xiongxiaotun <br/> 
 * 修改时间：2017年6月5日 下午12:28:28   <br/>  
 * 修改备注：    <br/> 
 * @version V1.0   <br/>
 */
@Component
public class TokenHelper {
	private final Logger logger = LoggerFactory.getLogger(TokenHelper.class);
	private static final ThreadLocal<String> tokenHolder = new ThreadLocal<String>();
	
	@Resource
	private RedisObjectClient redisObjectClient;
	
	public static void clearToken() {
		tokenHolder.remove();
	}
	
	public static void setToken(String token) {
		tokenHolder.set(token);
	}
	
	public static String getToken() {
		return tokenHolder.get();
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: generateToken  <br/>
	 * @Description: 生成token <br/>
	 * @param userUUID
	 * @param userName
	 * @return
	 * @version V1.0  <br/>
	 */
	public String generateToken(String userUUID, String userName){
		if(StringUtils.isBlank(userUUID)) {
			return null;
		}
		if(StringUtils.isBlank(userName)){
			return null;
		}
		try {
			String[] genKeyPair = ConfigTools.genKeyPair(516);
			//生成uuidMd5 使用 userName为盐值
			String uuidMd5 = MD5Util.getMD5Encode(userUUID + userName);
			//随机串
			String randomString = DateUtil.timestampTo14String(new Timestamp(new Date().getTime()));
			String token = ConfigTools.encrypt(genKeyPair[0], uuidMd5 + randomString);
			redisObjectClient.put(RedisKeyPrefix.TOKEN, genKeyPair[1], RedisKeyPrefix.PUBLIC_KEY);
			return token;
		} catch (Exception e) {
			logger.error("生成token出现异常。userUUID : {}, userName : {}.", e);
			throw new BaseException("999", "登录凭据生成发生异常");
		}
		
	}
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: validateToken  <br/>
	 * @Description: 验证token <br/>
	 * @param token
	 * @param userUUID
	 * @param userName
	 * @return
	 * @version V1.0  <br/>
	 */
	public boolean validateToken(String token, String userUUID, String userName){
		if(StringUtils.isBlank(token) || StringUtils.isBlank(userUUID) || StringUtils.isBlank(userName)){
			return false;
		}
		String publicKey = redisObjectClient.get(RedisKeyPrefix.TOKEN, RedisKeyPrefix.PUBLIC_KEY);
		try {
			String userUUIDAndTime = ConfigTools.decrypt(publicKey, token);
			if(StringUtils.isBlank(userUUIDAndTime) || userUUIDAndTime.length() < 19){
				return false;
			}
			String uuidMd5 = userUUIDAndTime.substring(0, userUUIDAndTime.length() - 19);
			if(StringUtils.isBlank(uuidMd5)){
				return false;
			}
			return uuidMd5.equals(MD5Util.getMD5Encode(userUUID + userName));
		} catch (Exception e) {
			logger.error("验证token出现异常。userUUID : {}, userName : {}.", e);
			throw new BaseException("999", "验证登录凭据发生异常");
		}
	}
}
